package leetcode.code0222;

import java.util.Stack;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;
import leetcode.helper.tree.TreeArray;
import leetcode.helper.tree.TreeNode;

public class Solution1 implements IDebug {

	public int countNodes(TreeNode root) {
		if (root == null) {
			return 0;
		}
		TreeNode node = root;
		int h = 0;
		while (node.left != null) {
			node = node.left;
			h += 1;
		}
		int l = (int) Math.pow(2, h);
		int r = l * 2 - 1;
		int ans = 0;
		while (l <= r) {
			int mid = l + ((r - l) >> 1);
			boolean exists = this.find(mid, root, h);
			if (exists) {
				r = mid - 1;
			} else {
				ans = mid;
				l = mid + 1;
			}
		}
		return ans;
	}

//	执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
//
//	内存消耗：43.9 MB, 在所有 Java 提交中击败了26.14%的用户
//
//	通过测试用例：18 / 18

	private boolean find(int num, TreeNode root, int h) {
		int check = 1 << (h - 1);
		TreeNode node = root;
		while (check > 0) {
			node = (num & check) == 0 ? node.left : node.right;
			check >>= 1;
		}
		return node == null;
	}

//	执行用时：1 ms, 在所有 Java 提交中击败了20.63%的用户
//
//	内存消耗：44 MB, 在所有 Java 提交中击败了19.05%的用户
//
//	通过测试用例：18 / 18
	private boolean find(int num, TreeNode root) {
		Stack<Integer> stack = new Stack<>();
		while (num > 0) {
			stack.add(num & 1);
			num >>= 1;
		}
		TreeNode node = root;
		stack.pop();
		while (!stack.isEmpty()) {
			int direction = stack.pop();
			node = direction == 1 ? node.right : node.left;
		}
		return node == null;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(6, this.countNodes(TreeArray.array2tree(HelpDebug.str2array4("[1,2,3,4,5,6]"))));

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution1 so = new Solution1();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
